package com.boomsecret.nio.simple;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author: wangjinliang
 * @date: 2020/10/20
 */
public class ClientDemo {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 11111))) {
            while (!socketChannel.finishConnect()) {
            }
        }

        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_WRITE);
        int count = selector.select();
        if (count > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isWritable()) {
                    socketChannel.write(ByteBuffer.wrap("abcdef".getBytes()));
                }
                iterator.remove();
            }
        }
        socketChannel.close();
    }
}
